package com.inxedu.os.edu.controller.email;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.inxedu.os.common.SendMail;
import com.inxedu.os.edu.pojo.*;
import com.inxedu.os.edu.service.emil.AdminEmailMsg;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("admin")
@Api(value = "邮箱接口", tags = "邮箱Controller")
public class AdminEmailController {
    @Autowired
    private AdminEmailMsg emailMsg;
    @InitBinder({"userEmailMsg"})
    public void initBinderSysFunction(WebDataBinder binder) {
        binder.setFieldDefaultPrefix("userEmailMsg.");
    }
    //邮箱管理查询
    @RequestMapping(value = "/email/sendEmaillist",method = {RequestMethod.GET,RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userEmailMsg",value = "邮箱信息",dataType = "userEmailMsg"),
            @ApiImplicitParam(name = "page",value = "分页",dataType = "page")
    })
    @ApiOperation(value = "根据对象查询邮箱信息",notes = "根据对象查询邮箱信息,模糊查询")
    public String toemil(Model model, @ModelAttribute("userEmailMsg")UserEmailMsg userEmailMsg,@RequestParam(defaultValue = "1")int page){
        PageHelper.startPage(page,10);
        List<EduEmailsendHistoryAndLoginname> list = emailMsg.GetEmailByExample(userEmailMsg);
        PageInfo<List<EduEmailsendHistoryAndLoginname>> info = new PageInfo(list);
        model.addAttribute("page",info);
        model.addAttribute("list",list);
        return  "view/inxedu/admin/email/sendEmail_list";
    }
//    @RequestMapping("/admin/email/")
//    public String goemil(Model model){
//        List<EduEmailsendHistoryAndLoginname> selectAll = emailMsg.selectAll();
//        model.addAttribute("list",selectAll);
//        return "view/inxedu/admin/email/sendEmail_list";
//    }
    //查看邮箱信息
    @RequestMapping(value = "/email/sendEmailMsgInfo/{id}",method = RequestMethod.GET)
    @ApiImplicitParam(name = "id",value = "邮箱id",dataType = "id")
    @ApiOperation(value = "查看邮箱信息",notes = "查看邮箱信息")
    public String lookemil(Model model, @PathVariable Integer id){
        EduEmailsendHistoryAndLoginname edu = emailMsg.GetEmailByid(id);
        model.addAttribute("userEmailMsg",edu);
        return "view/inxedu/admin/email/sendEmail_info";
    }
    //进入邮箱页面
    @RequestMapping(value = "/email/toEmailMsg",method = RequestMethod.GET)
    @ApiOperation(value = "进入发送邮件页面",notes = "进入发送邮件页面")
    public String goEmail(){
        return "/view/inxedu/admin/email/to_sendEmailMsg";
    }
//发送邮件
    @RequestMapping(value = "/email/sendEmailMsg",method = RequestMethod.POST)
    @ApiOperation(value = "发送邮件",notes = "发送邮件")
    @ResponseBody
    public result sendEmailMsg(HttpServletRequest request) throws ParseException, MessagingException, IOException {
        result result = new result();
        String emails = request.getParameter("linksman");
        String title = request.getParameter("title");
        String content = request.getParameter("content");
        int type = Integer.valueOf(request.getParameter("type"));
        String[] split = emails.split(",");
        Date time = new Date();
        if (type == 1) {
            for (String email:split
            ) {
                EduEmailsendHistoryWithBLOBs bloBs = new EduEmailsendHistoryWithBLOBs();
                bloBs.setCreateTime(time);
                bloBs.setSendTime(time);
                bloBs.setTitle(title);
                bloBs.setContent(content);
                bloBs.setEmail(email);
                bloBs.setUserId(1);
                bloBs.setStatus((byte) 1);
                bloBs.setType((byte)type);
                int a=  emailMsg.addEmail(bloBs);
                SendMail mail = new SendMail();
                List<String> list=new ArrayList<>();
                list.add(email);
                mail.setRecipients(list);
                mail.setSubject(title);
                mail.setDate(new Date());
                mail.setFrom("admin");
                mail.setContent(content,"text/html; charset=UTF-8");
                // 附件集合
                List<String> fileList = new ArrayList<String>();
                fileList.add("");
                mail.setMultiparts(fileList);
                mail.sendMessage();
            }
            result.setMessage("发送成功");
        }
        return result;
    }
    //发送跳转页面
    @RequestMapping(value = "/email/progressbar",method = RequestMethod.GET)
    @ApiImplicitParam(name = "type",value = "成功页面",dataType = "type")
    @ApiOperation(value = "发送成功跳转页面",notes = "发送成功跳转页面")
    public String sendEmail(javax.servlet.http.HttpServletRequest request, @RequestParam("type") int type){
        request.setAttribute("type",type);
        return "view/common/success";
    }
//@RequestMapping("/admin/query/progressbar")
//@ResponseBody
//public result getprogressbar(HttpServletRequest request,@RequestParam("type") int type){
//
//    double listNum=0;
//    double sumNum=0;
//    result result = new result();
//    result.setSumNum(sumNum);
//    result.setListNum(listNum);
//    return result;
//}
    //批量导入
    @RequestMapping(value = "/user/select_userlist/2",method = RequestMethod.GET)
    @ApiOperation(value = "批量导入学员",notes = "批量导入学员")
    public String getUserList(Model model){
        List<EduUser>  user= emailMsg.getUserList();
        model.addAttribute("list",user);
        return"view/inxedu/admin/email/select_user_list";
    }
    //文件上传
    @RequestMapping(value = "/email/importMsgExcel/{type}",method = RequestMethod.POST)
    @ApiOperation(value = "文件上传",notes = "文件上传")
    @ResponseBody
    public Result1 importExcel(HttpServletRequest request, @RequestParam("myFile") MultipartFile myFile, @PathVariable("type") int type) throws IOException {
        Result1 res=new Result1();
        HSSFWorkbook wookbook = new HSSFWorkbook(myFile.getInputStream());
        // 只读取sheet1
        HSSFSheet sheet = wookbook.getSheet("Sheet1");
        int rows = sheet.getLastRowNum();// Excel行数
        String mobileStr = "";
        for (int i = 1; i <= rows; i++) {
            // 读取左上端单元格
            HSSFRow row = sheet.getRow(i);
            // 行不为空
            if (row != null) {
                // **读取cell**
                HSSFCell cell = row.getCell((short) 0);
                if (cell != null) {
                    switch (cell.getCellType()) {
                        case HSSFCell.CELL_TYPE_FORMULA:
                            break;
                        case HSSFCell.CELL_TYPE_NUMERIC:
                            DecimalFormat df = new DecimalFormat("#");
                            mobileStr += df.format(cell.getNumericCellValue()) + ",";
                            break;
                        case HSSFCell.CELL_TYPE_STRING:
                            mobileStr += cell.getStringCellValue().trim() + ",";
                            break;
                        default:
                            break;
                    }
                }
            }
        }
        // 获得页面的
        if (request.getParameter("numerStr") != null && request.getParameter("numerStr") != "") {
            mobileStr += request.getParameter("numerStr");
        }
        request.setAttribute("numerStr",mobileStr);
        Map<String, Object> returnMap = null;
        // 邮箱页面
        returnMap = emailMsg.checkEmail(mobileStr);
        res.setEntity(mobileStr);
        res.setSuccess(true);
        res.setMessage("returnList");
        return res;
    }

}
